# -*- coding: utf-8 -*-
# File : init_configure.py
# Author: taoyahui
# Date : 2021/4/16
from utils.ansible_util import *
from utils.path_util import *
from results import *
from utils.path_util import *

import subprocess


def copy_ssh(ip, username, password, port):
    # 给copy.sh 赋权
    cmd = f"chmod u+x {get_root_dir()}/shell/copy.sh"
    sub = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
    sub.wait()
    output = sub.stdout.read()
    # print(output)

    # 运行copy.sh
    cmd = '.'+get_root_dir() + f"/shell/copy.sh {password} {username} {ip} {port}"
    print(cmd)
    sub = subprocess.Popen(get_root_dir() + f"/shell/copy.sh {password} {username} {ip} {port}", shell=True, stdout=subprocess.PIPE)
    sub.wait()
    output = sub.stdout.read()
    print(output)
    # result = os.system("ls")
    return output


def init_configure(ip, username, passwd, port):
    hosts = {'t_g': {'hosts':[{'ip':ip, 'username': username, 'password':passwd, 'port': port}]}}
    if int(copy_ssh(ip, username, passwd, port)) > 0:
        return sshpass_error_result
    mi = MyInventory()
    mi._dynamic_inventory(hosts)
    ansible = MyAnsiable(inventory=mi._inventory, connection='smart')
    extra_var = {
        'host': ip,
        'username': username,
        'local_path': get_root_dir() + '/wazuh-agent.rpm',
        'remote_path': '/root'
    }
    abs_path = get_root_dir()
    ansible.playbook(playbooks=[abs_path + '/playbook/centos_deploy_wazuh.yml'], var=extra_var)
    result = ansible.get_result()
    return result


if __name__ =='__main__':
    print(init_configure('10.16.81.153', 'root', '123456', 60122))
    # copy_ssh('10.16.85.44', 'root', 'ccit023130')
    # print(os.path.abspath())


